# -*- coding: utf-8 -*-
# __author__:heliujiang
# 2024/5/24 18:16

from unittest import TestCase

class TestAPI(TestCase):
    def setUp(self):
        # 在这里设置测试需要的前置条件，比如API客户端、测试数据等
        self.api_client = self.setup_api_client()
        self.expected_code = '0'  # 假设我们期望的code是'0'
        self.expected_message = 'Success'  # 假设我们期望的message是'Success'

    def setup_api_client(self):
        # 这里设置API客户端，例如requests.Session()或其他
        pass

    def assert_response(self, response, response_code=None, response_message=None):
        """
        断言HTTP响应的状态码以及JSON响应体中的code和message字段。

        :param response: 请求的响应对象
        :param response_code: 期望的code值
        :param response_message: 期望的message值
        """
        # 断言状态码
        self.assertEqual(response.status_code, 200, f"Expected status code to be 200, but got {response.status_code}")

        # 尝试解析JSON响应体
        try:
            response_data = response.json()
        except ValueError:
            self.fail("Response is not in JSON format")

        # 断言code和message
        if response_code is not None:
            self.assertEqual(response_data.get('code'), response_code,
                             f"Expected code to be {response_code}, but got {response_data.get('code')}")
        if response_message is not None:
            self.assertEqual(response_data.get('message'), response_message,
                             f"Expected message to be {response_message}, but got {response_data.get('message')}")

